<!DOCTYPE html>
<html lang="zh-cn"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/main.css" rel="stylesheet">

    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.ico" />

    <title>Go程序的 Strings 和 strconv 包 | wiseAI的小站</title>
</head><body><div class="container-fluid">
    <nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">
                <img src="/img/favicon.ico" alt="" width="30" height="24" class="d-inline-block align-text-top">
                wiseAI的小站
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/articles/">文章</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/categories/">分类</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/tags/">关键字</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/post/golang/">golang编程</a>
                    </li>
                    
                    <li class="nav-item">
                        <a  class="nav-link"   href="/about/">关于</a>
                    </li>
                    
                </ul>
                <form class="d-flex">
                    <input id="search-query" class="form-control me-2" type="search" placeholder="Search for anything..." aria-label="Search">
                </form>
            </div>
        </div>
    </nav>
</div>




<div id="content">
<div class="container article">
	<h1>Go程序的 Strings 和 strconv 包</h1>
	<div class="post-meta">
		<div>
			
			
			By wiseai | 2022-07-01 | 5 minutes
		</div>
		<div class="tags">
			
			<a class="btn btn-light links btn-sm" href="/tags/%E7%BC%96%E7%A8%8B/">编程</a>
			
		</div>
	</div>
	<div>
		<div class="article-post">
			<h1 id="47-strings-和-strconv-包">4.7 strings 和 strconv 包</h1>
<p>作为一种基本数据结构，每种语言都有一些对于字符串的预定义处理函数。Go 中使用 <code>strings</code> 包来完成对字符串的主要操作。</p>
<h2 id="471-前缀和后缀">4.7.1 前缀和后缀</h2>
<p><code>HasPrefix()</code> 判断字符串 <code>s</code> 是否以 <code>prefix</code> 开头：</p>
<pre tabindex="0"><code>strings.HasPrefix(s, prefix string) bool
</code></pre><p><code>HasSuffix()</code> 判断字符串 <code>s</code> 是否以 <code>suffix</code> 结尾：</p>
<pre tabindex="0"><code>strings.HasSuffix(s, suffix string) bool
</code></pre><pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strings&#34;
)
func main() {
	var str string = &#34;This is an example of a string&#34;
	fmt.Printf(&#34;T/F? Does the string \&#34;%s\&#34; have prefix %s? &#34;, str, &#34;Th&#34;)
	fmt.Printf(&#34;%t\n&#34;, strings.HasPrefix(str, &#34;Th&#34;))
}
</code></pre><p>输出：</p>
<pre><code>T/F? Does the string &quot;This is an example of a string&quot; have prefix Th? true
</code></pre>
<p>这个例子同样演示了转义字符 <code>\</code> 和格式化字符串的使用。</p>
<h2 id="472-字符串包含关系">4.7.2 字符串包含关系</h2>
<p><code>Contains()</code> 判断字符串 <code>s</code> 是否包含 <code>substr</code>：</p>
<pre tabindex="0"><code>strings.Contains(s, substr string) bool
</code></pre><h2 id="473-判断子字符串或字符在父字符串中出现的位置索引">4.7.3 判断子字符串或字符在父字符串中出现的位置（索引）</h2>
<p><code>Index()</code> 返回字符串 <code>str</code> 在字符串 <code>s</code> 中的索引（<code>str</code> 的第一个字符的索引），<code>-1</code> 表示字符串 <code>s</code> 不包含字符串 <code>str</code>：</p>
<pre tabindex="0"><code>strings.Index(s, str string) int
</code></pre><p><code>LastIndex()</code> 返回字符串 <code>str</code> 在字符串 <code>s</code> 中最后出现位置的索引（<code>str</code> 的第一个字符的索引），<code>-1</code> 表示字符串 <code>s</code> 不包含字符串 <code>str</code>：</p>
<pre tabindex="0"><code>strings.LastIndex(s, str string) int
</code></pre><p>如果需要查询非 ASCII 编码的字符在父字符串中的位置，建议使用以下函数来对字符进行定位：</p>
<pre tabindex="0"><code>strings.IndexRune(s string, r rune) int
</code></pre><pre><code>注: 原文为 &quot;If ch is a non-ASCII character use strings.IndexRune(s string, ch int) int.&quot;
该方法在最新版本的 Go 中定义为 func IndexRune(s string, r rune) int
实际使用中的第二个参数 rune 可以是 rune 或 int, 例如 strings.IndexRune(&quot;chicken&quot;, 99) 或 strings.IndexRune(&quot;chicken&quot;, rune('k'))
</code></pre>
<pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strings&#34;
)
func main() {
	var str string = &#34;Hi, I&#39;m Marc, Hi.&#34;
	fmt.Printf(&#34;The position of \&#34;Marc\&#34; is: &#34;)
	fmt.Printf(&#34;%d\n&#34;, strings.Index(str, &#34;Marc&#34;))
	fmt.Printf(&#34;The position of the first instance of \&#34;Hi\&#34; is: &#34;)
	fmt.Printf(&#34;%d\n&#34;, strings.Index(str, &#34;Hi&#34;))
	fmt.Printf(&#34;The position of the last instance of \&#34;Hi\&#34; is: &#34;)
	fmt.Printf(&#34;%d\n&#34;, strings.LastIndex(str, &#34;Hi&#34;))
	fmt.Printf(&#34;The position of \&#34;Burger\&#34; is: &#34;)
	fmt.Printf(&#34;%d\n&#34;, strings.Index(str, &#34;Burger&#34;))
}
</code></pre><p>输出：</p>
<pre><code>The position of &quot;Marc&quot; is: 8
The position of the first instance of &quot;Hi&quot; is: 0
The position of the last instance of &quot;Hi&quot; is: 14
The position of &quot;Burger&quot; is: -1
</code></pre>
<h2 id="474-字符串替换">4.7.4 字符串替换</h2>
<p><code>Replace()</code> 用于将字符串 <code>str</code> 中的前 <code>n</code> 个字符串 <code>old</code> 替换为字符串 <code>new</code>，并返回一个新的字符串，如果 <code>n = -1</code> 则替换所有字符串 <code>old</code> 为字符串 <code>new</code>：</p>
<pre tabindex="0"><code>strings.Replace(str, old, new string, n int) string
</code></pre><h2 id="475-统计字符串出现次数">4.7.5 统计字符串出现次数</h2>
<p><code>Count()</code> 用于计算字符串 <code>str</code> 在字符串 <code>s</code> 中出现的非重叠次数：</p>
<pre tabindex="0"><code>strings.Count(s, str string) int
</code></pre><pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strings&#34;
)
func main() {
	var str string = &#34;Hello, how is it going, Hugo?&#34;
	var manyG = &#34;gggggggggg&#34;
	fmt.Printf(&#34;Number of H&#39;s in %s is: &#34;, str)
	fmt.Printf(&#34;%d\n&#34;, strings.Count(str, &#34;H&#34;))
	fmt.Printf(&#34;Number of double g&#39;s in %s is: &#34;, manyG)
	fmt.Printf(&#34;%d\n&#34;, strings.Count(manyG, &#34;gg&#34;))
}
</code></pre><p>输出：</p>
<pre><code>Number of H's in Hello, how is it going, Hugo? is: 2
Number of double g’s in gggggggggg is: 5
</code></pre>
<h2 id="476-重复字符串">4.7.6 重复字符串</h2>
<p><code>Repeat()</code> 用于重复 <code>count</code> 次字符串 <code>s</code> 并返回一个新的字符串：</p>
<pre tabindex="0"><code>strings.Repeat(s, count int) string
</code></pre><pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strings&#34;
)
func main() {
	var origS string = &#34;Hi there! &#34;
	var newS string
	newS = strings.Repeat(origS, 3)
	fmt.Printf(&#34;The new repeated string is: %s\n&#34;, newS)
}
</code></pre><p>输出：</p>
<pre><code>The new repeated string is: Hi there! Hi there! Hi there!
</code></pre>
<h2 id="477-修改字符串大小写">4.7.7 修改字符串大小写</h2>
<p><code>ToLower()</code> 将字符串中的 Unicode 字符全部转换为相应的小写字符：</p>
<pre tabindex="0"><code>strings.ToLower(s) string
</code></pre><p><code>ToUpper()</code> 将字符串中的 Unicode 字符全部转换为相应的大写字符：</p>
<pre tabindex="0"><code>strings.ToUpper(s) string
</code></pre><pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strings&#34;
)
func main() {
	var orig string = &#34;Hey, how are you George?&#34;
	var lower string
	var upper string
	fmt.Printf(&#34;The original string is: %s\n&#34;, orig)
	lower = strings.ToLower(orig)
	fmt.Printf(&#34;The lowercase string is: %s\n&#34;, lower)
	upper = strings.ToUpper(orig)
	fmt.Printf(&#34;The uppercase string is: %s\n&#34;, upper)
}
</code></pre><p>输出：</p>
<pre><code>The original string is: Hey, how are you George?
The lowercase string is: hey, how are you george?
The uppercase string is: HEY, HOW ARE YOU GEORGE?
</code></pre>
<h2 id="478-修剪字符串">4.7.8 修剪字符串</h2>
<p>你可以使用 <code>strings.TrimSpace(s)</code> 来剔除字符串开头和结尾的空白符号；如果你想要剔除指定字符，则可以使用 <code>strings.Trim(s, &quot;cut&quot;)</code> 来将开头和结尾的 <code>cut</code> 去除掉。该函数的第二个参数可以包含任何字符，如果你只想剔除开头或者结尾的字符串，则可以使用 <code>TrimLeft()</code> 或者 <code>TrimRight()</code> 来实现。</p>
<h2 id="479-分割字符串">4.7.9 分割字符串</h2>
<p><code>strings.Fields(s)</code> 将会利用 1 个或多个空白符号来作为动态长度的分隔符将字符串分割成若干小块，并返回一个 slice，如果字符串只包含空白符号，则返回一个长度为 0 的 slice。</p>
<p><code>strings.Split(s, sep)</code> 用于自定义分割符号来对指定字符串进行分割，同样返回 slice。</p>
<p>因为这 2 个函数都会返回 slice，所以习惯使用 for-range 循环来对其进行处理（第 7.3 节）。</p>
<h2 id="4710-拼接-slice-到字符串">4.7.10 拼接 slice 到字符串</h2>
<p><code>Join()</code> 用于将元素类型为 string 的 slice 使用分割符号来拼接组成一个字符串：</p>
<pre tabindex="0"><code>strings.Join(sl []string, sep string) string
</code></pre><pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strings&#34;
)
func main() {
	str := &#34;The quick brown fox jumps over the lazy dog&#34;
	sl := strings.Fields(str)
	fmt.Printf(&#34;Splitted in slice: %v\n&#34;, sl)
	for _, val := range sl {
		fmt.Printf(&#34;%s - &#34;, val)
	}
	fmt.Println()
	str2 := &#34;GO1|The ABC of Go|25&#34;
	sl2 := strings.Split(str2, &#34;|&#34;)
	fmt.Printf(&#34;Splitted in slice: %v\n&#34;, sl2)
	for _, val := range sl2 {
		fmt.Printf(&#34;%s - &#34;, val)
	}
	fmt.Println()
	str3 := strings.Join(sl2,&#34;;&#34;)
	fmt.Printf(&#34;sl2 joined by ;: %s\n&#34;, str3)
}
</code></pre><p>输出：</p>
<pre><code>Splitted in slice: [The quick brown fox jumps over the lazy dog]
The - quick - brown - fox - jumps - over - the - lazy - dog -
Splitted in slice: [GO1 The ABC of Go 25]
GO1 - The ABC of Go - 25 -
sl2 joined by ;: GO1;The ABC of Go;25
</code></pre>
<p>其它有关字符串操作的文档请参阅 <a href="http://golang.org/pkg/strings/">官方文档</a>（ <strong>译者注：国内用户可访问 <a href="http://docs.studygolang.com/pkg/strings/">该页面</a></strong> ）。</p>
<h2 id="4711-从字符串中读取内容">4.7.11 从字符串中读取内容</h2>
<p>函数 <code>strings.NewReader(str)</code> 用于生成一个 <code>Reader</code> 并读取字符串中的内容，然后返回指向该 <code>Reader</code> 的指针，从其它类型读取内容的函数还有：</p>
<ul>
<li><code>Read()</code> 从 <code>[]byte</code> 中读取内容。</li>
<li><code>ReadByte()</code> 和 <code>ReadRune()</code> 从字符串中读取下一个 <code>byte</code> 或者 <code>rune</code>。</li>
</ul>
<h2 id="4712-字符串与其它类型的转换">4.7.12 字符串与其它类型的转换</h2>
<p>与字符串相关的类型转换都是通过 <code>strconv</code> 包实现的。</p>
<p>该包包含了一些变量用于获取程序运行的操作系统平台下 <code>int</code> 类型所占的位数，如：<code>strconv.IntSize</code>。</p>
<p>任何类型 <strong><code>T</code></strong> 转换为字符串总是成功的。</p>
<p>针对从数字类型转换到字符串，Go 提供了以下函数：</p>
<ul>
<li><code>strconv.Itoa(i int) string</code> 返回数字 <code>i</code> 所表示的字符串类型的十进制数。</li>
<li><code>strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string</code> 将 64 位浮点型的数字转换为字符串，其中 <code>fmt</code> 表示格式（其值可以是 <code>'b'</code>、<code>'e'</code>、<code>'f'</code> 或 <code>'g'</code>），<code>prec</code> 表示精度，<code>bitSize</code> 则使用 32 表示 <code>float32</code>，用 64 表示 <code>float64</code>。</li>
</ul>
<p>将字符串转换为其它类型 <strong><code>tp</code></strong> 并不总是可能的，可能会在运行时抛出错误 <code>parsing &quot;…&quot;: invalid argument</code>。</p>
<p>针对从字符串类型转换为数字类型，Go 提供了以下函数：</p>
<ul>
<li><code>strconv.Atoi(s string) (i int, err error)</code> 将字符串转换为 <code>int</code> 型。</li>
<li><code>strconv.ParseFloat(s string, bitSize int) (f float64, err error)</code> 将字符串转换为 <code>float64</code> 型。</li>
</ul>
<p>利用多返回值的特性，这些函数会返回 2 个值，第 1 个是转换后的结果（如果转换成功），第 2 个是可能出现的错误，因此，我们一般使用以下形式来进行从字符串到其它类型的转换：</p>
<pre><code>val, err = strconv.Atoi(s)
</code></pre>
<p>在下面这个示例中，我们忽略可能出现的转换错误：</p>
<p>示例 4.19 <a href="examples/chapter_4/string_conversion.go">string_conversion.go</a></p>
<pre tabindex="0"><code>package main
import (
	&#34;fmt&#34;
	&#34;strconv&#34;
)
func main() {
	var orig string = &#34;666&#34;
	var an int
	var newS string
	fmt.Printf(&#34;The size of ints is: %d\n&#34;, strconv.IntSize)	  
	an, _ = strconv.Atoi(orig)
	fmt.Printf(&#34;The integer is: %d\n&#34;, an) 
	an = an + 5
	newS = strconv.Itoa(an)
	fmt.Printf(&#34;The new string is: %s\n&#34;, newS)
}
</code></pre><p>输出：</p>
<pre><code>64 位系统：
The size of ints is: 64
32 位系统：
The size of ints is: 32
The integer is: 666
The new string is: 671
</code></pre>
<p>在第 5.1 节，我们将会利用 <code>if</code> 语句来对可能出现的错误进行分类处理。</p>
<p>更多有关该包的讨论，请参阅 <a href="http://golang.org/pkg/strconv/">官方文档</a>（ <strong>译者注：国内用户可访问 <a href="http://docs.studygolang.com/pkg/strconv/">该页面</a></strong> ）。</p>

		</div>
	</div>
</div>


<div class="container">
    
    <div class="row">
        
        <div class="col-5">
            <a class="page-link link-dark text-end dh" href="/post/golang/2022.06.30-%E5%AD%97%E7%AC%A6%E4%B8%B2/">
                <h5>前一篇</h5><br>
                Go程序的字符串
            </a>            
        </div>
        
        <div class="col-2">
        </div>
        
        <div class="col-5">
            <a class="page-link link-dark text-start dh" href="/post/golang/2022.07.05-%E6%97%B6%E9%97%B4%E5%92%8C%E6%97%A5%E6%9C%9F/">
                <h5>后一篇</h5><br>
                Go程序的时间和日期
            </a>            
        </div>
        
    </div>
    
</div>

        </div><br><br>
<footer class="container">
    <h2>友情链接</h2>
    <hr>
    <nav class="nav nav-pills flex-column flex-sm-row">
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/gnzg/index.html" target="_blank">孤鸟之歌</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/mm/index.html" target="_blank">生成随机字符</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/md/index.html" target="_blank">MarkDown</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://gitee.com/" target="_blank">Gitee</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://github.com/" target="_blank">Github</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.aliyun.com/" target="_blank">阿里云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://cloud.tencent.com/" target="_blank">腾讯云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.oschina.net/" target="_blank">OSCHINA开源中国</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://gitee.com/wiseai/the-way-to-go_ZH_CN/blob/master/eBook/directory.md" target="_blank">the way to go</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://topgoer.com/" target="_blank">golang文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://goframe.org/display/gf" target="_blank">GoFrame</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.aliyundrive.com/" target="_blank">阿里云盘</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://cn.vuejs.org/" target="_blank">vue3文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://element-plus.gitee.io/zh-CN/" target="_blank">element-plus文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.runoob.com/vue3/vue3-tutorial.html" target="_blank">vue3菜鸟教程</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://v5.bootcss.com/" target="_blank">bootstrap v5 中文文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.bootstrap.cn/" target="_blank">bootstrap文档</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://caddy2.dengxiaolong.com/docs/" target="_blank">caddy中文教程</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.58pic.com/" target="_blank">千图</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://ifonts.com/" target="_blank">iFonts</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://marketing.qiniu.com/" target="_blank">七牛云</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.ixigua.com/" target="_blank">西瓜视频</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/yugang/index.html" target="_blank">鱼缸计算</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://justcc.mengkang.net/#/" target="_blank">C语言JustCC</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://wiseai.gitee.io/pages/pptist/" target="_blank">PPTist</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="/index.xml" target="_blank">RSS</a>
        
        <a class="flex-sm-fill text-sm-center nav-link links link-dark" href="https://www.kancloud.cn/idcpj/python/418553" target="_blank">参考资料</a>
        
    </nav>

    <div class="copyright text-center">
      <span class="power-by">
        Powered by <a class="links" href="https://gohugo.io" target="_blank">Hugo</a>
    </span>
    <span>|</span>
    <span>
        Theme - <a class="links" href="https://github.com/wiseai-go/blog-hugo" target="_blank">WiseAI</a>
    </span>
    <br>
    <span class="copyright-year">
        &copy;
        
        2017 -
        2023<span>
            陇ICP备15000157号
            
        </span></span>

</div>
</footer>
<script src="/js/bootstrap.bundle.min.js"></script>


</body>
</html>
